#include <utility>
#include "gfaux_tools.h"
#include "jpeg_mem.h"
#include "j2k_mem.h"
#include "file_utilits.h"
#include "assert_macros.h"
using namespace gdface;
// jpeg 压缩质量默认值(全局)
static uint32_t default_jpeg_quality = 100U;
// jpeg 压缩质量默认值(当前线程)
static thread_local uint32_t tls_jpeg_quality = 0U;
namespace gdface {
	namespace image {
		void get_image_binary(const std::string & filename, std::string&out)
		{
			out = load_string(filename);
		}

		void get_image_binary(std::FILE * file, std::string&out)
		{
			throw_if_null(file)
				std::fseek(file, 0L, SEEK_END);
			auto filesize = std::ftell(file);
			std::vector<uint8_t>bin_data = std::vector<uint8_t>(size_t(filesize));
			out = std::string((char*)bin_data.data(), bin_data.size());
		}

		void get_image_binary(std::istream & stream, std::string&out)
		{
			auto bin = load_binary_stream(stream);
			out = std::string((char*)bin.data(), bin.size());
		}

		void get_image_binary(const char * filename, std::string&out)
		{
			out = load_string(filename);
		}
		void get_image_binary(const fs_image_matrix & matrix, std::string&out)
		{
			auto quality = tls_jpeg_quality ? tls_jpeg_quality : default_jpeg_quality;;
			out = jwp_save_jpeg_mem_as_string(matrix, quality);
		}
		void set_default_jpeg_quality(uint32_t quality)
		{
			if (quality <= 100 && quality > 0) {
				default_jpeg_quality = quality;
			}
		}
		void set_jpeg_quality(uint32_t quality)
		{
			if (quality <= 100 && quality > 0) {
				tls_jpeg_quality = quality;
			}
		}
		template<typename T>
		raii_string get_image_binary_raii(T input) {
			std::string out;
			get_image_binary(std::forward<T>(input), out);
			return raii_string(out);
		}
		gdface::raii_dll<std::string> get_image_binary_raii(const std::string&filename) {
			return get_image_binary_raii<decltype(filename)>(filename);
		}
		gdface::raii_dll<std::string> get_image_binary_raii(std::FILE *file) {
			return get_image_binary_raii<decltype(file)>(file);
		}
		gdface::raii_dll<std::string> get_image_binary_raii(std::istream&stream) {
			return get_image_binary_raii<decltype(stream)>(stream);
		}
		gdface::raii_dll<std::string> get_image_binary_raii(const char *filename) {
			return get_image_binary_raii<decltype(filename)>(filename);
		}

		gdface::raii_dll<std::string> get_image_binary_raii(const fs_image_matrix&matrix) {
			return get_image_binary_raii<decltype(matrix)>(matrix);
		}
		GAX_API fs_image_matrix decompress_jpeg_mem(const void * jpg, size_t size)
		{
			return jwp_load_jpeg_mem(jpg, size);
		}
		GAX_API fs_image_matrix decompress_jp2_mem(const void * jp2, size_t size)
		{
			return jwp_load_j2k_mem(jp2, size, FS_JPEG2K_CODEC_JP2);
		}
	} /* namespace image */
} /* namespace gdface */

